package cn.xhf.export.core;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.xhf.export.model.IndexModel;

public class TXTCore {
	 private static final String FILEPATH = PathKit.getWebRootPath() + File.separator + "upload" + File.separator ;

    /**
	 * 导出txt文件
	* @param tileName 
	* @param result
	* @param fileName
	* @return
	*/
	@SuppressWarnings("finally")
	public File initTXTCore(IndexModel index) {
		Map<String, String> tileName=index.getHead(); 
		String sql = index.getSql(); 
		String fileName=index.getFileName();
		List<Record> result = Db.find(sql);
		long start = System.currentTimeMillis();
		Map<String,Object> map = new HashMap<String, Object>();
		String relFilePath = null;// url
		BufferedWriter out = null;
		File file = null;
		try {
		    if (result != null && !result.isEmpty() && StringUtils.isNotEmpty(fileName)) {
		        fileName += "_" + System.currentTimeMillis() + ".txt";
		        File pathFile = new File(FILEPATH);
		        if (!pathFile.exists()) {
		            pathFile.mkdirs();
		        }
		        relFilePath = FILEPATH + File.separator + fileName;
		        file = new File(relFilePath);
		        if (!file.exists()) {
		            file.createNewFile();
		        }
		        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "GBK"));
		        for (int i = 0; i < result.size(); i++) {
		        	StringBuilder sb = new StringBuilder();
		        	int row = 0;
		        	for (String str : tileName.keySet()) {
		        		sb.append(tileName.get(str)+":"+result.get(i).getColumns().get(str));
		        		if(row != tileName.keySet().size()-1) {
		        			sb.append(",");
		        		}
		        		row ++ ;
					}
		        	out.write(sb.toString());
		        	out.newLine();
				}
		        System.out.println("写入文件耗时共*********************************" + (System.currentTimeMillis() - start) + "毫秒");
		    }
		} catch (IOException e) {
		    e.printStackTrace();
		} finally {
		    if (out != null) {
		        try {
		            out.flush();
		            out.close();
		        } catch (IOException e) {
		            e.printStackTrace();
		        }
		    }
		    map.put("mis", (System.currentTimeMillis() - start) + "毫秒");
		}
		return file;
	}
}
